package com.wuyan.locationdog.ui.login


import android.os.CountDownTimer
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import com.arcsoft.commonbase.R
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_device_info_modify
import com.arcsoft.commonbase.ext.afterTextChange
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.invisible
import com.arcsoft.commonbase.ext.isEmpty
import com.arcsoft.commonbase.ext.isTrimEmpty
import com.arcsoft.commonbase.ext.setPwdVisible
import com.arcsoft.commonbase.ext.textStringTrim
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.net.ApiService
import com.arcsoft.commonbase.widgets.ClearEditText
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.MainActivity
import com.wuyan.locationdog.databinding.RegisterActivityBinding
import com.wuyan.locationdog.ui.X5WebActivity
import com.wuyan.locationdog.viewmodel.LoginViewModel
import leifu.shapelibrary.ShapeView

class RegisterActivity : BaseBindingActivity<RegisterActivityBinding>() {

    private var countDownTimer: CountDownTimer? = null
    var isPwdVisible: Boolean = true
    private val mViewModel: LoginViewModel by viewModels()


    override fun initData() {
        setTitleText("", true)

        val type = intent.extras?.getInt("type")
        val isBindPhone = intent.extras?.getBoolean("isBindPhone")

        binding.apply {
            if (type == 6) {
                tvTitle.text = "重置密码"
                tvSubTitle.text = "系统会根据您选择的国家/地区的法律法规存储您的个人信息"
                btnLogin.setText("确认修改并登录")
            }
            SpanUtils.with(tvProtocol)
                .append("我已阅读并同意")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_6))
                .append("《使用协议》")
                .setForegroundColor(ColorUtils.getColor(R.color.text_color_selected))
                .setClickSpan(ColorUtils.getColor(R.color.text_color_selected), false) {
                    X5WebActivity.startAction(mActivity, ApiService.BASE_URL + "html/userAgreement.html")
                }
                .append(" ")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_6))
                .append("《隐私政策》")
                .setForegroundColor(ColorUtils.getColor(R.color.text_color_selected))
                .setClickSpan(ColorUtils.getColor(R.color.text_color_selected), false) {
                    X5WebActivity.startAction(mActivity, ApiService.BASE_URL + "html/privacyAgreement.html")
                }
                .create()





            btnMsg.setOnClickListener {
                //类型 1注册 2修改密码 3登录 4修改手机号(旧手机号) 5修改手机号(新手机号) 6找回密码
                val map = HashMap<String, Any>()
                map["phone"] = etPhone.textStringTrim()
                map["type"] = type.toString()
                mViewModel.getCode(map)
            }
            btnLogin.setOnClickListener {
                if (!cbProtocol.isChecked) {
                    customShowLong("请同意并阅读《使用协议》和《隐私政策》")
                    return@setOnClickListener
                }
                val map = HashMap<String, Any>()
                map["userPhone"] = etPhone.textStringTrim()
                map["phone"] = etPhone.textStringTrim()
                map["code"] = etMsg.textStringTrim()
                map["password"] = etPwd.textStringTrim()
                if (isBindPhone == true) {
                    //type == 8
                    mViewModel.bindPhone(map)
                } else if (type == 1) {
                    mViewModel.register(map)
                } else {
                    mViewModel.findPwd(map)
                }
            }
            //密码可见设置
            btnEye.setOnClickListener {
                etPwd.setPwdVisible(isPwdVisible, it as ImageView)
                isPwdVisible = !isPwdVisible
                etPwd.setSelection(etPwd.text?.length ?: 0)
            }


            onFocusChange(etPhone, phoneTip, phoneStroke)
            onFocusChange(etPwd, pwdTip, pwdStroke)
            onFocusChange(etMsg, msgTip, msgStroke)


            phoneTip.invisible()
            pwdTip.invisible()
            msgTip.invisible()

            loginEnable(etPhone, etMsg, etPwd)
        }


    }

    override fun observe() {
        mViewModel.yzmBean.observe(this) {
            customShowLong("成功")
            binding.msgCountDownTimer()
        }
        mViewModel.any.observe(this) {
            customShowLong("成功")
            Bus.post(bus_device_info_modify, binding.etPhone.textStringTrim())
            finish()
        }
        mViewModel.loginBean.observe(this) {
            SPUtils.getInstance().put("token", it.content.token)
            ActivityUtils.finishAllActivities()
            ActivityUtils.startActivity(MainActivity::class.java)
        }
    }


    private fun onFocusChange(editText: ClearEditText, tip: TextView, stroke: ShapeView) {
        editText.setFocusChangedListener { view, b ->
            if (b) {
                tip.visible()
                stroke.apply {
                    val color = ColorUtils.getColor(R.color.text_color_selected)
                    tip.setTextColor(color)
                    setShapeStrokeColor(color)
                    setUseShape()
                }
            } else {
                if (editText.isTrimEmpty()) {
                    tip.invisible()
                } else {
                    tip.visible()
                }
                stroke.apply {
                    val color = ColorUtils.getColor(R.color.text_color_unselected)
                    tip.setTextColor(color)
                    setShapeStrokeColor(color)
                    setUseShape()
                }
            }
        }
    }

    private fun RegisterActivityBinding.loginEnable(editText1: EditText, editText2: EditText, editText3: EditText) {
        if (editText1.isTrimEmpty() || editText2.isTrimEmpty() || editText3.isTrimEmpty()) {
            btnLogin.alpha = 0.4F
            btnLogin.isEnabled = false
        } else {
            btnLogin.alpha = 1F
            btnLogin.isEnabled = true
        }
        if (editText1.isTrimEmpty()) {
            btnMsg.alpha = 0.4F
            btnMsg.isEnabled = false
        } else {
            btnMsg.alpha = 1F
            btnMsg.isEnabled = true
        }
        editText1.afterTextChange {
            if (editText1.isTrimEmpty() || editText2.isTrimEmpty() || editText3.isTrimEmpty()) {
                btnLogin.alpha = 0.4F
                btnLogin.isEnabled = false
            } else {
                btnLogin.alpha = 1F
                btnLogin.isEnabled = true
            }

            if (editText1.isTrimEmpty()) {
                btnMsg.alpha = 0.4F
                btnMsg.isEnabled = false
            } else {
                btnMsg.alpha = 1F
                btnMsg.isEnabled = true
            }
        }
        editText2.afterTextChange {
            if (editText1.isTrimEmpty() || editText2.isTrimEmpty() || editText3.isTrimEmpty()) {
                btnLogin.alpha = 0.4F
                btnLogin.isEnabled = false
            } else {
                btnLogin.alpha = 1F
                btnLogin.isEnabled = true
            }
        }
        editText3.afterTextChange {
            if (editText1.isTrimEmpty() || editText2.isTrimEmpty() || editText3.isTrimEmpty()) {
                btnLogin.alpha = 0.4F
                btnLogin.isEnabled = false
            } else {
                btnLogin.alpha = 1F
                btnLogin.isEnabled = true
            }
        }

    }


    /**
     * 验证码倒计时
     */
    private fun RegisterActivityBinding.msgCountDownTimer() {
        if (etPhone.isEmpty()) {
            customShowLong("请输入手机号")
            return
        }
        if (!RegexUtils.isMobileSimple(etPhone.textStringTrim())) {
            customShowLong("请输入正确手机号码")
            return
        }
        if (countDownTimer == null) {
            countDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    btnMsg.isEnabled = false
                    btnMsg.text = (millisUntilFinished / 1000).toString() + "s后重发"
                    btnMsg.setTextColor(ColorUtils.getColor(R.color.text_color_unselected))
                }

                override fun onFinish() {
                    btnMsg.isEnabled = true
                    btnMsg.text = "获取验证码"
                    btnMsg.setTextColor(ColorUtils.getColor(R.color.text_color_selected))

                }
            }
        }
        countDownTimer?.start()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (countDownTimer != null) {
            countDownTimer?.cancel()
        }
    }
}

